package com.github.llyb120.qiuya.type;

import com.github.llyb120.qiuya.storage.Qiu;
import com.github.llyb120.qiuya.storage.VirtualFile;
import com.github.llyb120.qiuya.storage.bptree.BPlusTree;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;

import static com.github.llyb120.qiuya.storage.bptree.BPlusTree.INVALID_OFFSET;
import static com.github.llyb120.qiuya.util.Convert.*;

public class QCollectionIndex {

    Qiu qiu;

    //主键索引b+树
    BPlusTree bpTree;

    //数据区起始位置
    long dataOffset;

    //集合名
    String colName;

    //最大空余块数
    int maxFreeBlock;
    int maxColNameLen;

    private byte[] bytes;
    private LinkedList<Long> freeBlocks = new LinkedList<>();
//    private int start;

    public int byteLength(){
        //集合名（整数字节+最大长度）
        //最大空闲块 个数 + long字节 * 最大块
        //bptree的根节点 long字节
        return Integer.BYTES + maxColNameLen + (Integer.BYTES + maxFreeBlock * Long.BYTES) + Long.BYTES;
    }

    public QCollectionIndex(Qiu qiu, byte[] bytes, int start, int maxColNameLen, int maxFreeBlock){
        this.qiu = qiu;
        this.bytes = bytes;
        this.dataOffset = start;
        this.maxColNameLen = maxColNameLen;
        this.maxFreeBlock = maxFreeBlock;
        this.init();
    }

    void init(){
        int offset = 0;
        int strlen = byte2int(bytes, 0);
        offset += Integer.BYTES;
        colName = byte2String(bytes, offset, strlen);
        int blockCount = byte2int(bytes, offset);
        offset += Integer.BYTES;
        for (int i = 0; i < blockCount; i++) {
            freeBlocks.addLast(byte2long(bytes, offset));
            offset += Long.BYTES;
        }
        //读取头
        long bpTreeRoot = byte2long(bytes, offset);
        offset += Long.BYTES;
        if (bpTreeRoot == 0) {
            bpTreeRoot = INVALID_OFFSET;
        }
        bpTree = new BPlusTree(qiu.vf, bpTreeRoot);
    }

    public void flush(){

    }
}
